<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="search" placeholder="告警组/关键字/团队" class="filter-item" style="width: 400px;" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      v-if="list"
      :key="tableKey"
      v-loading="listLoading"
      :data="list.slice((currentPage - 1) * pageSize,currentPage * pageSize)"
      border
      fit
      highlight-current-row
      style="width: 90%"
    >

      <el-table-column label="告警组" prop="alertgroup" align="center" width="200" sortable>
        <template slot-scope="scope">
          <span>{{ scope.row.alertgroup }}</span>
        </template>
      </el-table-column>

      <el-table-column label="项目关键字" prop="alertname" align="center" width="300" sortable>
        <template slot-scope="scope">
          <span>{{ scope.row.alertname }}</span>
        </template>
      </el-table-column>

      <el-table-column label="来源关键字" prop="from" align="center" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.from }}</span>
        </template>
      </el-table-column>

      <el-table-column label="接收团队" prop="usergroup" align="center" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.usergroup }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="更新时间" prop="updated_at" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_at| parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="pageSize"
      :current.sync="currentPage"
      :page-sizes="pageSizes"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="100px" style="width:400px; margin-left:50px;">
        <el-form-item label="告警组" prop="alertgroup">
          <el-input v-model="temp.alertgroup" :readonly="dialogStatus=='update'" />
        </el-form-item>
        <el-form-item label="项目关键字" prop="alertname">
          <el-input v-model="temp.alertname" />
        </el-form-item>
        <el-form-item label="来源关键字" prop="from">
          <el-input v-model="temp.from" />
        </el-form-item>
        <el-form-item label="接收团队">
          <el-select
            v-model="selectedTeams"
            style="width:100%"
            clearable
            filterable
            allow-create
            default-first-option
            placeholder="请选择"
          >
            <el-option
              v-for="item in teamsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create'? createData(): updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime, arrToString } from '@/utils/index'
import Pagination from '@/components/Pagination'
import { getAllUsergroup, getAlertgroup, createAlertgroup, updateAlertgroup, deleteAlertgroup } from '@/api/alertm'

export default {
  name: 'LogTable',
  components: { Pagination },
  filters: {
    parseTime,
    arrToString
  },
  data() {
    return {
      tableKey: 0,
      notifyList: [],
      teamsList: null,
      selectedTeams: '',
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      temp: {
        alertgroup: '',
        alertname: '',
        from: '',
        usergroup: []
      },
      total: 0,
      currentPage: 1,
      pageSize: 10,
      pageSizes: [10, 20, 30],
      search: '',
      rawList: null,
      list: null,
      listLoading: true
    }
  },
  created() {
    this.getList()
    this.getTeamsList()
  },
  methods: {
    getTeamsList() {
      getAllUsergroup()
        .then(response => {
          var teams = []
          for (var i in response.data.data) {
            teams.push(response.data.data[i].usergroup)
          }
          this.teamsList = teams.map(item => {
            return { value: `${item}`, label: `${item}` }
          })
        })
        .catch(error => { console.log(error) })
    },
    getList() {
      this.listLoading = true

      // 后端返回数据格式
      // this.rawList = [
      //   {
      //     'alertgroup': 'canal-group',
      //     'alertname': '',
      //     'from': '(.*CannalMonitor)',
      //     'usergroup': 'canal-group'
      //   },
      //   {
      //     'alertgroup': 'db-Test-group',
      //     'alertname': '^(TestProblem.*)',
      //     'from': '^(Mysql|Redis|MongoDB)$',
      //     'usergroup': 'db-Test-group'
      //   },
      //   {
      //     'alertgroup': 'db-Internet-group',
      //     'alertname': '^(InternetProblem.*)',
      //     'from': '^(Mysql|Redis)$',
      //     'usergroup': 'db-Internet-group'
      //   },
      //   {
      //     'alertgroup': 'db-PlatformCrm-group',
      //     'alertname': '^(PlatformCrmProblem.*)',
      //     'from': '^(Mysql|Redis|MongoDB)$',
      //     'usergroup': 'db-PlatformCrm-group'
      //   }
      // ]
      // this.list = this.rawList
      // this.total = this.list.length
      // this.listLoading = false

      getAlertgroup()
        .then(response => {
          this.rawList = response.data.data
          this.list = this.rawList
          this.total = this.list.length
        })
        .catch(error => { console.log(error) })
        .finally(() => { this.listLoading = false })
    },

    handleFilter() {
      if (this.search.length === 0) {
        this.list = this.rawList
      } else {
        this.list = this.rawList.filter(data => !this.search || data.alertgroup.toLowerCase().includes(this.search.toLowerCase()))
        if (this.list.length === 0) {
          this.list = this.rawList.filter(data => !this.search || data.alertname.toLowerCase().includes(this.search.toLowerCase()))
        }
        if (this.list.length === 0) {
          this.list = this.rawList.filter(data => !this.search || data.from.toLowerCase().includes(this.search.toLowerCase()))
        }
        if (this.list.length === 0) {
          this.list = this.rawList.filter(data => !this.search || data.usergroup.toLowerCase().includes(this.search.toLowerCase()))
        }
      }
      this.total = this.list.length
    },

    resetTemp() {
      this.temp = {
        alertgroup: '',
        alertname: '',
        from: '',
        usergroup: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.selectedTeams = ''
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          this.temp.usergroup = this.selectedTeams
          createAlertgroup(this.temp)
            .then(res => {
              if (res.data.code === 200) {
                this.$notify({
                  title: res.data.status,
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: res.data.error,
                  type: 'error',
                  duration: 2000 })
              }
              this.getList()
            })
            .catch(error => { console.log(error) })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.selectedTeams = this.temp.usergroup
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          this.temp.usergroup = this.selectedTeams
          updateAlertgroup(this.temp.alertgroup, this.temp)
            .then(res => {
              if (res.data.code === 200) {
                this.$notify({
                  title: res.data.status,
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: res.data.error,
                  type: 'error',
                  duration: 2000 })
              }
              this.getList()
            })
            .catch(error => { console.log(error) })
        }
      })
    },
    handleDelete(index, row) {
      this.temp = Object.assign({}, row)
      deleteAlertgroup(this.temp.alertgroup)
        .then(res => {
          if (res.data.code === 200) {
            this.$notify({
              title: res.data.status,
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          } else {
            this.$notify({
              title: res.data.error,
              type: 'error',
              duration: 2000 })
          }
          this.getList()
        })
        .catch(error => { console.log(error) })
    }
  }
}
</script>

<style scoped>
.pagination-container {
  background: #fff;
  padding: 32px 16px;
}
</style>
